﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AppManager.Model;

namespace AppManager.BLL
{
    public class MessageDeviceBLL : BaseBLL<MessageDevice>
    {
        /// <summary>
        /// 更新sendstatus和 nextsendtime
        /// </summary>
        /// <param name="v1"></param>
        /// <param name="messageId"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public static void UpdateStatus(bool flag, List<MessageDevice> list)
        {
            //先查詢獲取最新數據
            var ids = list.Select(s => s.Id);
            var dbList = GetList(s => ids.Contains(s.Id));
            foreach (var item in dbList)
            {
                if (flag) //成功的话，时间推后10分钟，发送状态改成1
                {
                    item.NextSendTime = DateTime.Now.AddMinutes(10);
                    item.SendResult = true;
                }
                else
                {
                    item.SendResult = false;
                    item.FailSendCount += 1;
                }
            }
            UpdateAll(dbList);
        }

        /// <summary>
        /// 更新RemoteServerResult，FailSendCount
        /// </summary>
        /// <param name="isSuccess"></param>
        /// <param name="messageId"></param>
        /// <param name="deviceStr"></param>
        /// <returns></returns>
        public static void UpdateRemoteServer(bool isSuccess, int messageId, string deviceStr, string message = "")
        {
            if (isSuccess)
            {
                Db.Current.Database.ExecuteSqlCommand("delete from messagedevice where deviceStr={0} and messageId={1}", deviceStr, messageId);
            }
            else
            {
                var device = GetModel(s => s.MessageId == messageId && s.DeviceStr == deviceStr);
                if (device == null) return;
                if (!string.IsNullOrEmpty(message))
                {
                    device.Exception += "<<<" + DateTime.Now + Environment.NewLine + message + Environment.NewLine + ">>>";
                }
                device.FailSendCount += 1;
                Update(device);
            }
        }
    }
}
